//
//  CZEmoticonPackage.swift
//  EmoticonsDemo
//
//  Created by Summer on 2017/12/19.
//  Copyright © 2017年 Summer. All rights reserved.
//

import UIKit

/// 表情包模型
@objcMembers
class CZEmoticonPackage: NSObject {
    
    /// 分组名
    var bgImageName: String?
    
    /// 分组名
    var groupName: String?
    
    /// 目录，从目录加载 info.plist 可以创建表情模型数组
    var directory: String? {
        didSet {
            
            // 当设置目录时，从目录加载plist
            guard let directory = directory,
                let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
                let bundle = Bundle(path: path),
                let infoPath = bundle.path(forResource: "info.plist", ofType: nil, inDirectory: directory),
                let array = NSArray(contentsOfFile: infoPath) as? [[String: String]],
                let models = NSArray.yy_modelArray(with: CZEmoticon.self, json: array) as? [CZEmoticon] else {
                return
            }
            
            for m in models {
                m.directory = directory
            }
            
            emoticons += models
        }
    }
    
    /// 表情模型数组
    /// 使用懒加载，可以避免后续的解包
    lazy var emoticons = [CZEmoticon]()
    
    /// 每个页签下表情需要的页数
    var numberOfPages: Int {
        return (emoticons.count - 1) / 20 + 1
    }
    
    func emoticon(page: Int) -> [CZEmoticon] {
        // 每页最多20个表情
        let count = 20
        let location = page * count
        var length = count
        
        // 判断数组越界(最后一页可能表情少于20个)
        if location + length > emoticons.count {
            length = emoticons.count - location
        }
        
        // 截取数组的子数组
        let range = NSRange(location: location, length: length)
        let subArray = (emoticons as NSArray).subarray(with: range)
        return subArray as! [CZEmoticon]
    }
    
    override var description: String {
        return yy_modelDescription()
    }
    
}
